const WpsCom = require("./wps_com");
const qs = require("querystring");
const setCookieParser = require("set-cookie-parser");
const CommonAxerrHG = require("../../tool/CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{
 * wpscom:WpsCom}}>}
 * @param {String} mail 
 * @param {String} pass 
 */
function loginByAccountWpsCom(mail, pass) {
  return new Promise(resolve => {
    let axios = require("./wps_axios");
    // debugger
    let csrf = WpsCom.CreateCsrfToken()
    let data = qs.stringify({
      account: mail,
      password: pass,
      cb: "https://drive.wps.com/",
      from: "cloudwelcome",
      source: "web",
      keeponline: 1,
      csrfmiddlewaretoken: csrf
    })
    // data = "cb=https%3A%2F%2Fdrive.wps.com%2F&from=cloudwelcome&source=web&account=hujimiya%40yandex.com&password=wps65huji&keeponline=1&csrfmiddlewaretoken=wB26pd3atthwE8YdKb6b5BirQwFKT3jk"
    axios.post(`https://account.wps.com/p/signin?_=${Date.now()}`, data, {
      headers: {
        Referer: 'https://account.wps.com/?cb=https://drive.wps.com/&from=cloudwelcome',
        'content-type': 'application/x-www-form-urlencoded',//非常重要
        'X-Requested-With': 'XMLHttpRequest',
        Origin: "https://account.wps.com",
        accept: "application/json",
        cookies: `csrf=${csrf}; 838e4074e1e14758821ae2a46c9fef88=WyIyMTc4NTA2NDk0Il0; captcha=; wpsqing_autoLoginV1=1;`
      },
      validateStatus: s => s == 200
    }).then(axresp => {
      // debugger
      if (axresp.data
        && axresp.data.result == "ok"
        && axresp.headers["set-cookie"]) {
        let parsed = setCookieParser.parse(axresp.headers["set-cookie"]);
        // debugger
        let wps_sid_obj = parsed.find(e => e.name == "wps_sid" && e.value.length >= 8);
        if (wps_sid_obj) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              wpscom: new WpsCom(wps_sid_obj.value, csrf)
            }
          })
        }
        return CommonAxerrHG(resolve)(`headers set-cookie don't have wps_sid:${JSON.stringify(axresp.headers["set-cookie"])}`)
      }
      throw { data: axresp.data, headers: axresp.headers };
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr)
    })
  })
}

module.exports = {
  loginByAccountWpsCom
}